<?php
/**
 * @Copyright (c) 2011, 新浪网运营部-网络应用开发部
 * All rights reserved.
 * MC基类
 * @author          wangxin <wangxin3@staff.sina.com.cn>
 * @time            2011/3/2 11:48
 * @version         Id: 0.9
*/

class BaseModelMemcache {

    static private $memcache = array(); //MC连接池

    private $mc; //当前MC链接

    /*
     * @params string $mcName MC名称
     * @params array $mcConfig eg:array('servers'=>'192.168.1.1:7600 192.168.1.2:7700');
     */
    public function __construct($mcName = '', $servers = '') {
        empty($mcName) && $mcName = MC_DEFAULT;
        $servers = empty($servers) ? constant(strtoupper("MC_" . $mcName . "_SERVERS")) : $servers;
        Common::debug($servers, 'mc_connect');
        $mcKey = md5($servers);
        if (self::$memcache[$mcKey] instanceof Memcache) {
            $this->mc = self::$memcache[$mcKey];
        } else {
            self::$memcache[$mcKey] = new Memcache();
            $serverArr = explode (" ", $servers);
            foreach ($serverArr as $v) {
                list($server, $port) = explode(":", $v);
                self::$memcache[$mcKey]->addServer($server, $port);
            }
            $this->mc = self::$memcache[$mcKey];
        }
    }
    
    public function set($key, $value, $time = 0) {
        $key = MC_KEY_PREFIX . $key;
        Common::debug($key, 'KEY_SET');
        Common::debug($value, 'CACHE_SET');
        return $this->mc->set($key, $value, 0, $time);
    }

    public function get($key) {
        if (HttpParams::get('_flush_cache') == 1) {
            return false;
        }
        $key = MC_KEY_PREFIX . $key;
        Common::debug($key, 'KEY_GET');
        $data = $this->mc->get($key);
        Common::debug($data, 'CACHE_GET');
        return $data;
    }

    public function delete($key) {
        $key = MC_KEY_PREFIX . $key;
        Common::debug($key, 'KEY_DELETE');
        //查看要被delete的信息是否正确
        $data = $this->mc->get($key);
        return $this->mc->delete($key);
    }
}
?>
